function request(options) {
  let userInfo = wx.getStorageSync('userInfo');
  if (userInfo == null || userInfo == undefined || userInfo == '') {
    const userInfoNologin = {
      avatarUrl: "/images/nologin.png",
      nickName: "授权登录"
    };
    wx.setStorageSync('userInfo', userInfoNologin);
    console.log("请登录！");
    wx.navigateTo({
      url: '/pages/login/login',
    });
    return Promise.reject("用户未登录");
  } else {
    // const API_ROOT = "http://192.168.1.2:8088";
    const API_ROOT = "http://192.168.2.50:8088";
    return new Promise((resolve, reject) => {
      refreshToken(API_ROOT, userInfo)
        .then(() => {
          wx.request({
            ...options,
            url: API_ROOT + options.url,
            success: function (res) {
              if (res.statusCode === 200) {
                resolve(res.data);
              } else {
                reject(res.errMsg);
              }
            },
            fail: function (err) {
              reject(err.errMsg);
            },
          });
        })
        .catch(error => {
          reject(error);
        });
    });
  }
}

// 更新 Token
function refreshToken(url, userInfo) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url + "/user/updateTokenTime",
      method: 'GET',
      data: { 'token': userInfo.token },
      success: res => {
        if (res.data == "offline") {
          const userInfoNologin = {
            avatarUrl: "/images/nologin.png",
            nickName: "授权登录"
          };
          
          wx.setStorageSync('userInfo', userInfoNologin);
          wx.navigateTo({
            url: '/pages/login/login',
          });
          
          reject("用户已离线");
        } else {
          userInfo.token = res.data;
          wx.setStorageSync('userInfo', userInfo);
          resolve();
        }
      },
      fail: error => {
        console.log(error);
        reject(error);
      }
    });
  });
}

export default request;
